<template>
  <div style="padding: 10px 20px">
    <!-- CRF名称：{{ treeWithCrfList[nextCrfTreeNum].crfName }} -->
    <div style="text-align: center; font-size: 20px; margin: 10px 0"></div>
    <VFormRender
      :form-json="formJson"
      :form-data="formData"
      :option-data="optionData"
      ref="vFormRef"
      @formChange="onFormDataChange"
    >
    </VFormRender>
    <div style="display: flex; justify-content: center; margin-top: 10px">
      <!-- <el-button type="primary" plain :icon="Back" @click="handleBringIntoMenu(0)"
            >暂 存</el-button
          > -->
      <!-- <el-button
            type="primary"
            plain
            @click="handleLastNext(0)"
            :icon="DArrowLeft"
            v-if="nextCrfTreeNum != 0"
            >LAST</el-button
          > -->
      <el-button
        type="primary"
        plain
        @click="handleLastNext(1)"
        v-show="treeWithCrfList.length != 0"
        v-if="nextCrfTreeNum != treeWithCrfList.length - 1"
        >NEXT
        <el-icon class="el-icon--right"><DArrowRight /></el-icon>
      </el-button>
      <el-button
        type="primary"
        plain
        :icon="Check"
        @click="handleSubmit"
        v-if="nextCrfTreeNum === treeWithCrfList.length - 1"
        >提 交</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { Back, Check, DArrowRight, DArrowLeft } from '@element-plus/icons-vue';
import { getTrialDetail, phoneCrf, collectInfoSubmit } from '@/api/trial/trial';
import VFormRender from '@/components/form-render/index.vue';
import { treeWithCrf } from '@/api/group/group';
import { getDetail } from '@/api/crf/crf.js';
import { ref, reactive, computed, onMounted, defineEmits, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const router = useRouter();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
const formJson = ref({});
const vFormRef = ref(null);
const formData = ref({});
const optionData = ref({});
let nextCrfTreeNum = ref(0);
let treeWithCrfList = ref([]);
onMounted(() => {
  if (routerQuery.value.groupId) {
    initPhoneCrf(routerQuery.value.groupId);
  }
});
const initPhoneCrf = async groupId => {
  let res = await phoneCrf(groupId);
  console.log(res);
  let DATA = res.data.data;
  treeWithCrfList.value = DATA;
  // treeWithCrfList.value = extractChildren(DATA);
  // flowList.value = res.data.data;
  // crfSelectOptions.value = flowList.value;
  getDetailData(DATA[0].crf);
};
const getDetailData = async crfId => {
  const { data: res } = await getDetail(crfId);
  console.log('CRF的detail有值吗', res);
  if (res.code == 200) {
    formJson.value = JSON.parse(res.data.content);
    nextTick(() => {
      console.log(vFormRef.value);
      vFormRef.value.setFormJson(formJson.value);
    });
  }
};

// 下一个crf按钮
/* 
  type 0:上一个
  type 1:下一个
*/
const handleLastNext = type => {
  let treeWithCrfListVal = treeWithCrfList.value[nextCrfTreeNum.value];
  if (type === 0 && nextCrfTreeNum.value != 0) {
    nextCrfTreeNum.value = nextCrfTreeNum.value - 1;
  } else if (type === 1 && nextCrfTreeNum.value != treeWithCrfList.value.length - 1) {
    nextCrfTreeNum.value = nextCrfTreeNum.value + 1;
  }
  console.log('点击下一步', optionData.value, formData.value, treeWithCrfListVal);
  vFormRef.value.getFormData().then(res => {
    let form = {
      content: JSON.stringify(res),
      trial: treeWithCrfListVal.trialId,
      groupId: treeWithCrfListVal.groupId,
      phaseId: treeWithCrfListVal.pahseId || null,
      crfId: treeWithCrfListVal.crf,
      caseUserId: routerQuery.value.caseUserId || null,
      linkId: treeWithCrfListVal.linkId,
      type: treeWithCrfListVal.type,
    };
    console.log(form);
    collectInfoSubmit(form).then(res => {
      getDetailData(treeWithCrfList.value[nextCrfTreeNum.value].crf);
    });
  });

  // getDetailData(treeWithCrfList.value[nextCrfTreeNum.value].crf);

  // if (nextCrfTreeNum.value != treeWithCrfList.value[0].crfList.length - 1) {
  //   nextCrfTreeNum.value = nextCrfTreeNum.value + 1;
  //   getDetailData(treeWithCrfList.value[0].crfList[nextCrfTreeNum.value].crf);
  // }
};
const onFormDataChange = data => {
  console.log(data);
  formData.value = data;
};
// 递归提取所有children项
const extractChildren = data => {
  let result = [];

  data.forEach(item => {
    if (item.crfList) {
      result = result.concat(item.crfList); // 将当前项的children加入结果数组
      result = result.concat(extractChildren(item.crfList)); // 递归处理子项
    }
  });

  return result;
};
// 提交按钮
const handleSubmit = () => {
  let treeWithCrfListVal = treeWithCrfList.value[nextCrfTreeNum.value];
  vFormRef.value.getFormData().then(res => {
    let form = {
      content: JSON.stringify(res),
      trial: treeWithCrfListVal.trialId,
      groupId: treeWithCrfListVal.groupId,
      phaseId: treeWithCrfListVal.phaseId || null,
      crfId: treeWithCrfListVal.crf,
      caseUserId: treeWithCrfListVal.clinicalCaseId || null,
      linkId: treeWithCrfListVal.id,
      type: treeWithCrfListVal.type,
    };
    console.log(form);
    collectInfoSubmit(form).then(res => {
      ElMessage.success('提交成功！可前往后台查看！');
      setTimeout(() => {
        router.replace({
          path: '/CrfH5',
          query: {
            ...routerQuery.value,
          },
        });
      }, 1000);
      // getDetailData(treeWithCrfList.value[nextCrfTreeNum.value].crf);
    });
  });
};
</script>